package com.caipiao.crawler.lotteryNumber;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.caipiao.constant.CrawlerConstants;
import com.caipiao.crawler.model.LotteryNumber;
import com.caipiao.crawler.page.BasePageProcessor;
import us.codecraft.webmagic.Page;

/**
 * Created by adminitrator on 2018/7/28.
 */
public class LotteryNumberResultPage extends BasePageProcessor {

    @Override
    public void process(Page page) {
        String url = page.getUrl().toString();
        System.out.println(url);
        if(url.contains("history")) {
            //历史页面,获取id
            processHistory(page);
        } else {
            //处理接口数据
            processData(page);
        }
    }

    public void processData(Page page) {
        String data = page.getJson().get();
        JSONObject obj = (JSONObject) ((JSONArray) JSON.parse(data)).get(0);
        JSONObject lottery = obj.getJSONObject("lottery");
        LotteryNumber model = new LotteryNumber();
        model.setPrize_detail(data); //全部数据，用于返回前端
        model.setTerm(lottery.getString("term"));
        model.setDate(lottery.getString("openTime_fmt1"));
        model.setNumber(lottery.getString("number"));
        model.setCreated_time((int) (System.currentTimeMillis()/1000L));
        model.setType(0);
        page.putField("model", model);
    }

    public void processHistory(Page page) {
        page.setSkip(true);  //不需要传到pipeline
        String id = page.getHtml().xpath("//div[@class='result']/table/tbody/tr/td[1]/text()").toString();
        if(id == null) {
            //TODO error 日志
            return;
        }
        String targetUrl = CrawlerConstants.DALETOU_DATA_URL + id;
        page.addTargetRequest(targetUrl);
    }
}
